import React, { PureComponent } from 'react';
import {Input} from 'antd';
import styles from './index.less'
const {TextArea} = Input;

export default class Inputs extends PureComponent {

    static getDerivedStateFromProps(nextProps) {
        // Should be a controlled component.         
        if ('value' in nextProps) {
          return {
            ...(nextProps),
            value:nextProps.value?nextProps.value : '',
            num:nextProps.maxLength?(nextProps.value||'').length:(nextProps.value||'').length,
          };
        }
        return null;
      }
  
    constructor(props) {
        super(props);                
        const value = props.value || '';  
        const maxLength = props.maxLength;                 
        this.state = {
          //num:maxLength?value.substr(0,maxLength).length:value.length,
          num:props.num,
           value,
          maxLength,
        };
    }       
  onChange = (e) => {
    const { onChange } = this.props;    
    this.setState({
        num:e.target.value.length,
        value:e.target.value
    })
    this.props.onChange(e.target.value)    
  } 

  onBlur= (e) => {
    const {onBlur} = this.props;
    if(typeof onBlur === 'function') onBlur(e);
  }

  render() {
    const {
      type,    
      showtotal, 
      autoFocus,
      rows    
    } = this.props;     
    const { num,maxLength,value,  } = this.state;      
    return (
        <div className={styles["Input-container"]}> 
            {
              type==='textarea'?
              (
                <TextArea
                  onChange={this.onChange} 
                  {...this.props} 
                  maxLength={maxLength}  
                  value={value} 
                  onBlur={this.onBlur} 
                  autoFocus={autoFocus}
                ></TextArea>
              ):
              (
                <Input  
                  onChange={this.onChange} 
                  {...this.props} 
                  maxLength={maxLength}  
                  value={value} 
                  onBlur={this.onBlur} 
                  autoFocus={autoFocus}
                />
              )
            }                    
            {
                showtotal &&  maxLength/1?<span className={styles.total} style={{lineHeight:`${type=='textarea'?rows?40*rows:80:40}px`}}>{num}/{maxLength}</span>:null
            }            
        </div>
    );
  }
}

Inputs.defaultProps = {
  showtotal: true
}
